<?php

namespace App\Services;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

use Illuminate\Support\Facades\Cache;
use Exception;

class AuthToken
{
    function __construct()
    {

    }

    /**
     * Token配置
     *
     * @return array
     */
    public static function config()
    {
        return [
            'token_key' => 'php-jwt@uniqid#123456',
            'token_exp' => 1
        ];
    }

    /**
     * Token生成
     *
     * @param array $data
     */
    public static function create($data, $expires)
    {
        $config = self::config();

        $payload = [
            'iat' => time(), // 签发时间
            'nbf' => time(), // 生效时间
            //'exp' => time() + $config['token_exp'] * 3600, // 过期时间
            'exp' => $expires,
            'data' => $data,
        ];

        $key = $config['token_key']; // 密钥
        $token = JWT::encode($payload, $key, 'HS256');

        return $token;
    }

    /**
     * Token验证
     *
     * @param string $token token
     */
    public static function verify($token)
    {
        $config = self::config();

        try {
            $key = $config['token_key'];
            $decode = JWT::decode($token, new Key($key, 'HS256'));
            $admin = $decode->data;

            return $admin;
        } catch (\Exception $e) {
            return [];
        }
    }
}
